const md5 = require("md5");
const userinfo = require("../database/userinfo");
const verify = require("../modules/verify");

module.exports = async (req, res)=>{
  const { token, oldPassword, newPassword } = req.body;

  if(!(token && oldPassword && newPassword)){
    res.send({
      code: 0,
      msg:"缺少必传参数：token，oldPassword，newPassword",
      data:null
    })
    return;
  }

  try{
    const tokenData = await verify(token);
    const userData = await userinfo.find({ userId: tokenData.id });
    if(userData[0].password === md5(oldPassword)){
      await userinfo.updateOne({ userId: tokenData.id }, {
        password: md5(newPassword)
      });
      res.send({
        code:1,
        msg:"密码修改成功",
        data: null
      })
    }else{
      res.send({
        code:4,
        msg:"老密码不符",
        data:null
      })
    }
  }catch(err){
    if(err.name === "JsonWebTokenError"){
      res.send({
        code: 3,
        msg: "登录失效或未登录",
        data: null
      })
    }else{
      res.send({
        code: 2,
        msg: "数据库出错",
        data: err.toString()
      })
    }
  }
}